<?php


namespace app\crontab\controller\always;


use custom\Log;
use custom\Redis;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\Exception;

/**
 * 自动维护到时未开拍的拍卖记录
 * Class AutoUpdateAuctionStatus
 * @package app\crontab\controller
 */
class AutoUpdateAuctionStatus extends Command {

    protected function configure() {
        $this->setName('AutoUpdateAuctionStatus');
    }

    protected function execute(Input $input, Output $output) {
        try {
            $wait = 0;
            while (1):
                $now_time = time();
                echo '当前时间戳:' . $now_time;
                echo "\n";
                //修改到时未开拍状态
                db("house_auction")
                    ->where('start_time', '<=', $now_time)
                    ->where('auction_status', 1)
                    ->update(['auction_status' => 2]);
                //快要开始的最近一条
                $start_time = db("house_auction")
                    ->order('start_time asc')
                    ->where('auction_status', 1)
                    ->value('start_time');
                if (empty($start_time)) {
                    $wait++;
                    if ($wait >= 3) {
                        echo "没有需要处理的数据\n";
                        break;
                    }
                    echo "等待第{$wait}次\n";
                    sleep(60 * 30);
                    continue;
                }
                //不处理大于当天的
                if ($start_time > strtotime(date('Y-m-d', $now_time) . ' 23:59:59')) {
                    echo "当天没有需要处理的数据\n";
                    break;
                }
                $diff_time = $start_time - $now_time;
                if ($diff_time <= 0) {
                    continue;
                }
                echo "睡眠：{$diff_time}秒\n";
                sleep($diff_time);
            endwhile;
        } catch (Exception $e) {
            $err = "异常信息:{$e->getMessage()} | 异常所在的代码行:{$e->getLine()} | 异常文件{$e->getFile()}" . "\r\n\r\n";
            Log::write($err, "AutoUpdateAuctionStatus_Err.log");
        }
    }
}